<?php
declare (strict_types=1);

namespace app\controller\api\v1\user\mine;

use app\service\logic\common\finance\FinanceCoinService;
use app\validate\common\user\CoinValidate;
use think\App;
use app\controller\api\ApiController;
use app\service\logic\common\user\CoinService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;

class CoinController extends ApiController
{
    protected $service;

    public function __construct(App $app, CoinService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }

    /**
     * 显示资源列表
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index(): Json
    {
        $params = $this->request->param();
        $search_fields = $this->service->getSearchColumn();
        $search = request()->only($search_fields);

        $this->validate($params, CoinValidate::class . '.index');
        $search['user_id'] = $this->request->middleware('user')['id'];

        $fun = function ($model) {
            $model['type_map'] = $this->service->getTypeMap($model['type']);
            // 1 返币 2 消费 3 提现 4 退款
            $model['coin_count_map'] = in_array($model['type'], [1,4]) ? '+' . $model['coin_count'] : '-' . $model['coin_count'];
            return $model;
        };
        $result = $this->service->getList($params, $search_fields, $search, [], $fun);
        return amis($result);
    }

    /**
     * 提现
     *
     * @return Json
     */
    public function cash()
    {
        $params = $this->request->param();
        $this->validate($params, CoinValidate::class . '.cash');
        $user = $this->request->middleware('user');
        $params['user_id'] = $user['id'];

        $result = invoke(FinanceCoinService::class)->cashOperate($params);
        return amis($result);
    }
}
